import {
  getWithdrawal,
  deleteWithdrawal,
  putWithdrawal,
  getStoresByNameLike,
} from '../../../services/api';

export default {
  namespace: 'withdrawal',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *fetch({ payload: currentPage }, { call, put }) {
      const response = yield call(getWithdrawal, currentPage);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *remove({ payload: index, callback }, { call, put, select }) {
      const list = yield select(state => state.facilitator.data.list);
      yield call(deleteWithdrawal, list[index].id);
      yield put({
        type: 'delete',
        payload: index,
      });
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const { status } = payload;
      const response = yield call(putWithdrawal, payload.id, { status });
      yield put({
        type: 'replace',
        payload: {
          editableIndex: payload.editableIndex,
          response,
        },
      });
      if (callback) callback();
    },
    *search(payload, { call, put }) {
      const { nameLike } = payload;
      const response = yield call(getStoresByNameLike, nameLike);
      yield put({
        type: 'save',
        payload: response,
      });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    append(state, action) {
      const { list } = state.data;
      list.unshift(action.payload);
      const total = state.data.pagination.total + 1;
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
            total,
          },
        },
      };
    },
    delete(state, action) {
      const { list } = state.data;
      list.splice(action.payload, 1);
      const total = state.data.pagination.total - 1;
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
            total,
          },
        },
      };
    },
    replace(state, action) {
      const { list } = state.data;
      list.splice(action.payload.editableIndex, 1, action.payload.response);
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
          },
        },
      };
    },
  },
};
